<script lang="ts" setup>
import { ref, watch, computed, nextTick } from 'vue'
import wjzs from '@/components/wjzs.vue'
import wjfwService from '@/api/wjfw'
import { ElMessage } from 'element-plus'
// 入参
const props = defineProps({
  // 旋转角度
  currentItem: {
    type: Object,
    default: () => ({}),
  },
})

const fileUrl = computed(() => {
  return `${window.IPCONFIG}/fpi/wjfw/download?wjbh=${props.currentItem?.wjxh}`
})
const pdfUrl = ref('')
const wjzsRef = ref()
watch(
  () => props.currentItem,
  (val: any) => {
    if (val.wjhz === '.pdf' || val.wjhz === 'pdf') {
      const params = { wjbh: val.wjxh }
      wjfwService.downloadBlob(params).then((res) => {
        if (res.type === 'application/json') {
          const reader = new FileReader()
          reader.onload = () => {
            const jsonData =
              typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
            ElMessage({ type: 'warning', message: jsonData.message })
          }
          reader.readAsText(res)
        } else {
          pdfUrl.value = window.URL.createObjectURL(res)
          nextTick(() => {
            wjzsRef.value?.init()
          })
        }
      })
    } else {
      nextTick(() => {
        pdfUrl.value = fileUrl.value
        wjzsRef.value?.init()
      })
    }
  },
  { deep: true },
)

const fileType = computed(() => {
  if (
    [
      '.jpg',
      '.png',
      '.gif',
      '.jpeg',
      'jpg',
      'png',
      'gif',
      'jpeg',
      '.tiff',
      'tiff',
      'bmp',
      '.bmp',
    ].includes(props.currentItem?.wjhz)
  )
    return 'img'
  if (['.pdf', 'pdf'].includes(props.currentItem?.wjhz)) return 'pdf'
  if (['.doc', 'doc', '.docx', 'docx', '.wps', 'wps'].includes(props.currentItem?.wjhz))
    return 'word'
  if (['.ofd', 'ofd'].includes(props.currentItem?.wjhz)) return 'ofd'
  if (['.mp4', 'mp4'].includes(props.currentItem?.wjhz)) return 'mp4'
  return ''
})
</script>
<template>
  <div class="preview-box">
    <video
      style="width: 100%; height: 100%"
      v-if="fileType === 'mp4'"
      :src="fileUrl"
      controls
      controlsList="nodownload"
    />
    <wjzs
      v-else-if="['img', 'word', 'ofd', 'pdf'].includes(fileType)"
      ref="wjzsRef"
      :wjlx="fileType"
      :url="pdfUrl"
    />
    <el-empty v-else :description="`暂不支持${props.currentItem?.wjhz}格式文件预览`" />
  </div>
</template>
<style lang="scss" scoped>
.preview-box {
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;
  justify-content: center;
}
.footer {
  padding-right: 20px;
  padding-top: 10px;
  text-align: right;
}
</style>
